/**
 * Created by Admin on 04.01.2015.
 */

var GlShaderControl = (function ($) {
    return $.inherit({
        shader: null,
        gl: null,
        sceneObjects: null,

        addObject: function (id, sceneObject) {
            this.sceneObjects[id] && this.sceneObjects[id]._destroy();
            this.sceneObjects[id] = sceneObject;
        },

        addObjects: function (sceneObjects) {
            var shaderControl = this;
            sceneObjects && $.each(sceneObjects, function (id, sceneObject) {
                shaderControl.addObject(id, sceneObject);
            })
        },

        _initSceneObjects: function (sceneObjects) {
            this.sceneObjects = {};
            this.addObjects(sceneObjects);
        },

        __constructor: function (glShader, gl, sceneObjects) {
            this.shader = glShader;
            this.gl = gl;
            this._initSceneObjects(sceneObjects);
        },

        render: function (prerender, postrender) {
            var gl = this.gl;
            prerender = prerender || $.noop;
            postrender = postrender || $.noop;
            var shader = this.shader;
            gl.useProgram(this.shader.program);
            $.each(this.sceneObjects, function (_, sceneObject) {
                prerender(sceneObject);
                sceneObject.animate();
                sceneObject.bindAttributes(shader.attributes);
                sceneObject.setUniforms(shader.uniforms);
                sceneObject.render();
                postrender(sceneObject);

            });

        }
    })
})(window["jQuery"]);